package com.stony.core.keygenerator;

import java.util.Date;

import com.eaoa.dao.pub.PubBillcodeDAO;
import com.eaoa.query.pub.PubBillcodeQuery;
import com.eaoa.vo.pub.PubBillcode;
import com.stony.core.bo.HibernateBusinessObject;
import com.stony.core.util.CoreUtils;

public class FillCodeBO extends HibernateBusinessObject {

	private String billcode;
	private PubBillcode po;
	private Long currentno;
	
	private static PubBillcodeDAO bilcodeDAO = new PubBillcodeDAO();

	public FillCodeBO(String billcode) {
		super();

		this.billcode = billcode;

	}

	protected void performBusinessLogic() {

		long longone = 1;
		
		po= PubBillcodeQuery.loadByCode(billcode);
		currentno = po.getCurrentno();
		
		PubBillcode tmp = (PubBillcode)bilcodeDAO.loadAndLock(po.getBillcodeno());
		tmp.setCurrentno(new Long(tmp.getCurrentno().longValue() + longone));
		bilcodeDAO.update(tmp);

	}

	/**
	 * ABCyyyyMM-0001
	 * @return
	 */
	public String getNewCode() {
		String result = "" ;
		String code = po.getBillcode();
		String date = CoreUtils.getFourBitYearMonth(new Date());
		String count = CoreUtils.padLeft(CoreUtils.formatString(po.getCurrentno()), 4, '0');
		if(code.indexOf("_")!=-1){
			String[] codes = code.split("_");
			result = codes[0] + date + codes[1] + count;
		}else{
			result = code + date + "-" + count;
		}
		return result;
	}
	
	/**
	 * ABC0001
	 * @return
	 */
	public String getSimpleCode() {
		String newCode = po.getBillcode()
		+ CoreUtils.padLeft(CoreUtils.formatString(po.getCurrentno()),
				4, '0');
		return newCode;
	}
	
	public Long getCurrentno(){
		return currentno;
	}

}
